package org.classdef.analyzer.info.method;

import org.classdef.analyzer.info.ClassDef;
import org.classdef.analyzer.info.accesstype.MethodAccessType;
import org.classdef.analyzer.info.attribute.AttributePool;
import org.classdef.analyzer.info.constant.ConstantInfo;
import org.classdef.analyzer.info.methodtype.MethodType;

/**
 * 
 * 方法描述信息
 *
 */
public class MethodInfo {
	private short accessFlags;
	private short nameIndex;
	private short descriptorIndex;
	private short attributesCount;
	private AttributePool attributePool;
	
	protected ClassDef def;

	public MethodInfo(short accessFlags, short nameIndex,
			short descriptorIndex, short attributesCount,
			AttributePool attributePool) {
		this.accessFlags = accessFlags;
		this.nameIndex = nameIndex;
		this.descriptorIndex = descriptorIndex;
		this.attributesCount = attributesCount;
		this.attributePool = attributePool;
	}

	/**
	 * @return accessFlags
	 */
	public short getAccessFlags() {
		return accessFlags;
	}

	/**
	 * @return nameIndex
	 */
	public short getNameIndex() {
		return nameIndex;
	}

	/**
	 * @return descriptorIndex
	 */
	public short getDescriptorIndex() {
		return descriptorIndex;
	}

	/**
	 * @return attributesCount
	 */
	public short getAttributesCount() {
		return attributesCount;
	}

	/**
	 * @return attributePool
	 */
	public AttributePool getAttributePool() {
		return attributePool;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"accessFlags\":").append(accessFlags);
		sb.append(",\"access\":\"").append(MethodAccessType.getType(accessFlags)).append("\"");
		sb.append(",\"nameIndex\":").append(nameIndex);
		sb.append(",\"name\":\"").append(getName()).append("\"");
		sb.append(",\"descriptorIndex\":").append(descriptorIndex);
		sb.append(",\"descriptor\":\"").append(MethodType.getType(getConst(descriptorIndex).getValue().toString())).append("\"");
		sb.append(",\"attributesCount\":").append(attributesCount);
		sb.append(",\"attributePool\":").append(attributePool);
		sb.append("}");
		return sb.toString();
	}
	
	private ConstantInfo getConst(int index){
		return def.getConstantPool().get(index);
	}
	
	private String getName(){
		String name = getConst(nameIndex).getValue().toString();
		if("<init>".equals(name)){
			String[] strs = getConst(def.getThisClass()).getValue().toString().split("/");
			return strs[strs.length - 1];
		}else if("<clinit>".equals(name)){
			return "static{}";
		}else {
			return name;
		}
	}
}